# from datetime import datetime # 原来用的注释掉
from django.utils import timezone as datetime # 不想大面积修改就这么做

from django.http import JsonResponse
from myadmin.models import User
import random


def login(request):
    '''执行登录'''
    try:
        # 根据登录账号获取用户信息
        uname = request.POST.get('username')
        user = User.objects.get(username=uname)
        if user.status <= 0 or user.status > 4:
            return JsonResponse({'state': 0, 'msg': '账户无效'})
        # 校验当前用户状态
        else:
            # 获取密码并md5
            import hashlib
            md5 = hashlib.md5()
            n = user.password_salt
            s = request.POST['password'] + str(n)
            md5.update(s.encode('utf-8'))
            # 校验密码是否正确
            if user.password_hash == md5.hexdigest():
                # 将当前登录成功用户信息以adminuser这个key放入到session中
                request.session['adminuser'] = user.toDict()
                ustatus = user.status
                return JsonResponse({'state': ustatus, 'msg': '登陆成功'})
            else:
                return JsonResponse({'state': 0, 'msg': '登录密码错误'})
    except Exception as err:
        print(err)
        return JsonResponse({'state': 0, 'msg': '账号无效'})


def logout(request):
    '''执行退出'''
    del request.session['adminuser']
    # return redirect(reverse('myadmin_login'))
    return JsonResponse({'state': 0, 'msg': '退出登录'})


def register(request):
    '''注册'''
    uname = request.POST.get('username')
    # print(uname)
    if User.objects.filter(username=uname).exists():
        ob = User.objects.get(username=uname)
        if ob.status == 0:
            ob.status = 1
            ob.nickname = request.POST.get('nickname')
            # 获取密码并md5
            import hashlib
            md5 = hashlib.md5()
            n = random.randint(100000, 999999)
            s = request.POST['password'] + str(n)  # 从表单获取密码并添加干扰值
            md5.update(s.encode('utf-8'))  # 将要产生md5的字串放进去
            ob.password_hash = md5.hexdigest()  # 获取md5值
            ob.password_salt = n
            ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            ob.save()
            return JsonResponse({'state': 1, 'msg': '注册成功'})
        else:
            return JsonResponse({'state': 0, 'msg': '账户已存在'})
    else:
        ob = User()
        ob.username = uname
        ob.nickname = request.POST['nickname']
        # 获取密码并md5
        import hashlib
        md5 = hashlib.md5()
        n = random.randint(100000, 999999)
        s = request.POST['password'] + str(n)  # 从表单获取密码并添加干扰值
        md5.update(s.encode('utf-8'))  # 将要产生md5的字串放进去
        ob.password_hash = md5.hexdigest()  # 获取md5值
        ob.password_salt = n

        ob.status = 1
        ob.create_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.update_at = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        ob.save()
        return JsonResponse({'state': 1, 'msg': '注册成功'})
